﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Marketing.SalesPromotions
{
    public class SalesPromotionManager : DomainService
    {
        private readonly IRepository<SalesPromotion> _salesPromotionRepository;

        public SalesPromotionManager(
            IRepository<SalesPromotion> salesPromotionRepository
            )
        {
            _salesPromotionRepository = salesPromotionRepository;
        }

        public async Task<SalesPromotion> Create(SalesPromotion salesPromotion)
        {
            return await _salesPromotionRepository.InsertAsync(salesPromotion);
        }

        public async Task<SalesPromotion> Update(SalesPromotion salesPromotion)
        {
            return await _salesPromotionRepository.UpdateAsync(salesPromotion);
        }

        public async Task Delete(int id)
        {
            await _salesPromotionRepository.DeleteAsync(id);
        }

        public async Task<SalesPromotion> Get(int id)
        {
            return await _salesPromotionRepository.GetAsync(id);
        }

        public async Task<List<SalesPromotion>> GetAll(bool mustBeValid = false)
        {
            if (mustBeValid)
            {
                return await _salesPromotionRepository.GetAllListAsync(r => r.IsOngoing);
            }
            else
            {
                return await _salesPromotionRepository.GetAllListAsync();
            }
        }

        public async Task<List<SalesPromotion>> GetAllOfCommodity(int commodityId, bool mustBeValid = false)
        {
            var query = _salesPromotionRepository.GetAll().Where(r => (r.TargetType == SalesPromotionTargetType.All || r.AppliedCommodityIds.Items.Contains(commodityId)));
            if (mustBeValid)
            {
                query = query.Where(r => r.IsOngoing);
            }
            return query.OrderByDescending(r => r.CreationTime).ToList();
        }

        /// <summary>
        /// 得到所有在限时活动中的商品ID，如果返回null，说明所有商品都是限时活动商品
        /// </summary>
        /// <returns></returns>
        public async Task<List<int>> GetInPromotionCommodityIds()
        {
            var items = await GetAll(true);
            var result = new List<int>();
            foreach(var item in items)
            {
                if (item.TargetType == SalesPromotionTargetType.All) return null;
                else result = result.Union(item.AppliedCommodityIds.Items).ToList();
            }
            return result;
        }
    }
}
